package funcs

import (
	"time"

	"github.com/didi/nightingale/src/common/dataobj"
	"github.com/didi/nightingale/src/modules/agent/core"
	"github.com/didi/nightingale/src/modules/agent/sys"

	"github.com/toolkits/pkg/logger"
	"github.com/toolkits/pkg/nux"
)

var (
	historyNetStat  map[string]uint64
	lastTimeNetStat time.Time
)

func NetstatTcpExtMetrics() (ret []*dataobj.MetricValue) {
	tcpExtMetricsMap := sys.Config.TcpExtMetricsMap
	ret = make([]*dataobj.MetricValue, 0)
	newNetStat, err := nux.Netstat("TcpExt")
	if err != nil {
		logger.Warning(err)
		return
	}
	now := time.Now()
	interval := now.Unix() - lastTimeNetStat.Unix()
	lastTimeNetStat = now
	if historyNetStat == nil {
		historyNetStat = newNetStat
		logger.Info("historyNetStat is nil")
		return
	}
	for item, newvalue := range newNetStat {
		oldValue := historyNetStat[item]
		v := float64(newvalue-oldValue) / float64(interval)
		if _, ok := tcpExtMetricsMap[item]; ok {
			ret = append(ret, core.GaugeValue("netstat.TcpExt."+item, v, ""))
		}
	}
	historyNetStat = newNetStat
	return
}
